package com.rexense.beacon.service;

import com.rexense.beacon.alg.Trilateral;
import com.rexense.beacon.alg.weighted.WeightedTrilateral;
import com.rexense.beacon.entity.Beacon;
import com.rexense.beacon.entity.Location;
import com.rexense.beacon.entity.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class LocationService {

    @Autowired
    private BaseDataService baseDataService;

    @Autowired
    private LabelService labelService;

    public boolean locate(List<Msg> msgList) {
        if (msgList != null && msgList.size() >= 3) {
            List<String> beaconIds = msgList.stream().map(Msg::getBeaconId).collect(Collectors.toList());
            List<Beacon> beaconList = baseDataService.listBeacons(beaconIds);
            if (beaconList != null) {
                Map<String, Beacon> beaconMap = beaconList.stream().collect(Collectors.toMap(Beacon::getBeaconId, beacon -> beacon));
                Location location = WeightedTrilateral.locate(msgList, beaconMap);
                Location location1 = Trilateral.locate(msgList, beaconMap);
                String labelId = msgList.get(0).getLabelId();
                String msgId = msgList.get(0).getMsgId();
                labelService.setLabelLocation(labelId, msgId, location);
                return true;
            }
        }
        return false;
    }

}
